import sys
from PySide6.QtWidgets import QApplication, QMainWindow, QWidget, QHBoxLayout, QVBoxLayout, QLabel, QMenuBar, QMenu, QSplitter, QTabWidget, QGridLayout, QLineEdit, QPushButton
from status_bar.status_bar import StatusBar
from PySide6.QtCore import Qt, QSize, QCoreApplication
from PySide6.QtGui import QIcon, QGuiApplication
from session.ui import SessionTree
from theme.manager import ThemeManager
from theme.ui import ThemePanel
from terminal.ui import Terminal
from terminal.tabs import TabManager
from logger.ui import LoggerPanel
from logger.manager import LogManager
from settings.ui import SettingsPanel
from utility.ui import UtilityPanel
import os

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.init_window()
        self.init_managers()
        self.init_menu()
        self.init_ui()
        self.apply_theme(self.theme_manager.get_current_theme())
        
    def init_window(self):
        """初始化窗口基本设置"""
        self.setWindowTitle("ATerminal")
        
        # 设置窗口图标
        icon_path = os.path.join(os.path.dirname(__file__), 'static', 'icons', 'app.ico')
        if os.path.exists(icon_path):
            app_icon = QIcon(icon_path)
            self.setWindowIcon(app_icon)
            QApplication.setWindowIcon(app_icon)  # 设置应用程序级别的图标
        
        # 设置窗口基础大小
        base_width = 1280
        base_height = 800
        
        # 获取屏幕尺寸
        screen = QApplication.primaryScreen().geometry()
        # 计算窗口居中位置
        x = (screen.width() - base_width) // 2
        y = (screen.height() - base_height) // 2
        
        # 设置窗口大小和位置
        self.setGeometry(x, y, base_width, base_height)
        self.showMaximized()
        
    def init_managers(self):
        """初始化管理器实例"""
        self.theme_manager = ThemeManager()
        self.log_manager = LogManager()
        
    def init_ui(self):
        """初始化UI组件"""
        self.setup_central_widget()
        self.setup_status_bar()
        
    def setup_central_widget(self):
        """设置中央部件"""
        central_widget = QWidget()
        central_widget.setObjectName("central_widget")
        self.setCentralWidget(central_widget)
        main_layout = QVBoxLayout(central_widget)
        main_layout.setObjectName("main_layout")
        main_layout.setContentsMargins(0, 0, 0, 0)
        main_layout.setSpacing(0)
        
        top_container = self.create_terminal_container()
        main_layout.addWidget(top_container)
        
    def create_terminal_container(self):
        """创建终端容器"""
        terminal_container = QWidget()
        terminal_layout = QHBoxLayout(terminal_container)
        terminal_layout.setContentsMargins(0, 0, 0, 0)
        terminal_layout.setSpacing(0)
        
        main_splitter = self.create_main_splitter()
        terminal_layout.addWidget(main_splitter)
        
        return terminal_container
        
    def create_main_splitter(self):
        """创建主分割器"""
        main_splitter = QSplitter(Qt.Orientation.Horizontal)
        main_splitter.setObjectName("main_splitter")
        
        left_container = self.create_left_container()
        center_container = self.create_center_container()
        right_container = self.create_right_container()
        
        main_splitter.addWidget(left_container)
        main_splitter.addWidget(center_container)
        main_splitter.addWidget(right_container)
        
        return main_splitter
        
    def create_left_container(self):
        """创建左侧容器（会话列表）"""
        left_container = QWidget()
        left_container.setObjectName("left_container")
        left_container.setMinimumWidth(240)
        left_container.setMaximumWidth(320)
        
        layout = QVBoxLayout(left_container)
        layout.setContentsMargins(10, 10, 10, 10)
        layout.setSpacing(8)
        
        search_box = QLineEdit()
        search_box.setPlaceholderText("搜索会话...")
        search_box.setObjectName("search_box")
        
        self.session_list = SessionTree()
        self.session_list.itemDoubleClicked.connect(self.on_session_double_clicked)
        search_box.textChanged.connect(self.session_list.filter_sessions)
        
        layout.addWidget(search_box)
        layout.addWidget(self.session_list)
        
        return left_container
        
    def create_center_container(self):
        """创建中央容器（终端标签页）"""
        center_container = QWidget()
        center_container.setObjectName("center_container")
        
        layout = QVBoxLayout(center_container)
        layout.setSpacing(0)
        
        # 添加无会话提示标签
        self.no_session_label = QLabel("无激活会话")
        self.no_session_label.setObjectName("no_session_label")
        self.no_session_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
        layout.addWidget(self.no_session_label)
        
        # 创建会话内容区
        self.session_content = TabManager(center_container)
        self.session_content.setObjectName("session_content")
        layout.addWidget(self.session_content)
        
        # 根据会话数量更新标签显示状态
        self.session_content.currentChanged.connect(self._update_no_session_label)
        self._update_no_session_label()
        
        return center_container
        
    def _update_no_session_label(self, index=None):
        """更新无激活会话标签的显示状态"""
        if self.session_content.count() == 0:
            self.no_session_label.show()
            self.session_content.hide()
        else:
            self.no_session_label.hide()
            self.session_content.show()
        
    def create_right_container(self):
        """创建右侧容器（辅助功能区）"""
        right_container = QWidget()
        right_container.setObjectName("right_container")
        right_container.setMinimumWidth(230)
        right_container.setMaximumWidth(400)
        
        # 为right_container添加布局
        right_layout = QVBoxLayout(right_container)
        right_layout.setSpacing(0)
        
        self.utility_panel = UtilityPanel(right_container)
        right_layout.addWidget(self.utility_panel)
        
        return right_container
        
    def create_settings_container(self):
        """创建设置容器"""
        settings_container = QWidget()
        settings_container.setObjectName("settings_container")
        layout = QVBoxLayout(settings_container)
        layout.setContentsMargins(0, 0, 0, 0)
        layout.setSpacing(0)
        
        self.settings_panel = SettingsPanel(self.theme_manager, self.log_manager, self)
        layout.addWidget(self.settings_panel)
        
        settings_container.hide()
        return settings_container
        
    def setup_status_bar(self):
        """设置状态栏"""
        self.status_bar = StatusBar()
        self.centralWidget().layout().addWidget(self.status_bar)
        

    def apply_theme(self, theme):
        """应用主题样式"""
        qss = self.theme_manager.get_theme_qss(theme)
        self.setStyleSheet(qss)
        
    def on_session_double_clicked(self, item):
        """处理会话双击事件"""
        session_data = item.data(0, Qt.ItemDataRole.UserRole)
        if session_data and session_data['config']['type'] == 'session':
            session_name = item.text(0)
            terminal = self.session_content.create_terminal_tab(session_name, session_data)
            terminal.connection_status_changed.connect(self.update_status_bar)
            
    def update_status_bar(self, session_type=None, params=None, connected=False):
        """更新状态栏信息"""
        self.status_bar.update_status(session_type, params, connected)


    def on_nav_button_clicked(self, clicked_btn):
        """处理导航按钮点击事件"""
        # 更新所有按钮的选中状态
        for btn in self.nav_buttons:
            btn.setProperty("selected", btn == clicked_btn)
            btn.style().unpolish(btn)
            btn.style().polish(btn)
        
        # 切换容器显示
        is_terminal = clicked_btn.toolTip() == "终端"
        is_version = clicked_btn.toolTip() == "版本"
        
        self.terminal_container.setVisible(is_terminal)
        self.version_container.setVisible(is_version)

    def init_menu(self):
        """初始化菜单栏"""
        menubar = self.menuBar()
        
        # 文件菜单
        file_menu = menubar.addMenu('文件')
        exit_action = file_menu.addAction('退出')
        exit_action.triggered.connect(self.close)
        
        # 设置菜单
        settings_menu = menubar.addMenu('设置')
        theme_action = settings_menu.addAction('主题设置')
        theme_action.triggered.connect(self.show_settings)
        terminal_action = settings_menu.addAction('终端设置')
        terminal_action.triggered.connect(lambda: self.show_settings(1))
        log_action = settings_menu.addAction('日志设置')
        log_action.triggered.connect(lambda: self.show_settings(2))
        
        # 帮助菜单
        help_menu = menubar.addMenu('帮助')
        about_action = help_menu.addAction('关于')
        about_action.triggered.connect(self.show_about)
    
    def show_container(self, container_type):
        """显示指定容器"""
        self.terminal_container.setVisible(container_type == 'terminal')
        self.version_container.setVisible(container_type == 'version')
        
        # 更新导航按钮状态
        for btn in self.nav_buttons:
            is_selected = (btn.toolTip() == '终端' and container_type == 'terminal') or \
                         (btn.toolTip() == '版本' and container_type == 'version')
            btn.setProperty('selected', is_selected)
            btn.style().unpolish(btn)
            btn.style().polish(btn)
    
    def show_settings(self, tab_index=0):
        """显示设置对话框"""
        from PySide6.QtWidgets import QDialog
        dialog = QDialog(self)
        dialog.setWindowTitle('设置')
        dialog.setMinimumWidth(800)
        dialog.setMinimumHeight(600)
        
        layout = QVBoxLayout(dialog)
        settings_panel = SettingsPanel(self.theme_manager, self.log_manager, self)
        layout.addWidget(settings_panel)
        
        # 切换到指定的设置标签页
        if hasattr(settings_panel, 'stack_widget'):
            settings_panel.stack_widget.setCurrentIndex(tab_index)
            if tab_index == 0:
                settings_panel.theme_btn.setProperty('selected', True)
                settings_panel.terminal_btn.setProperty('selected', False)
                settings_panel.logger_btn.setProperty('selected', False)
            elif tab_index == 1:
                settings_panel.theme_btn.setProperty('selected', False)
                settings_panel.terminal_btn.setProperty('selected', True)
                settings_panel.logger_btn.setProperty('selected', False)
            elif tab_index == 2:
                settings_panel.theme_btn.setProperty('selected', False)
                settings_panel.terminal_btn.setProperty('selected', False)
                settings_panel.logger_btn.setProperty('selected', True)
            
            settings_panel.theme_btn.style().unpolish(settings_panel.theme_btn)
            settings_panel.theme_btn.style().polish(settings_panel.theme_btn)
            settings_panel.terminal_btn.style().unpolish(settings_panel.terminal_btn)
            settings_panel.terminal_btn.style().polish(settings_panel.terminal_btn)
            settings_panel.logger_btn.style().unpolish(settings_panel.logger_btn)
            settings_panel.logger_btn.style().polish(settings_panel.logger_btn)
        
        # 连接设置面板的保存信号
        settings_panel.save_settings = lambda: self._apply_settings_changes(settings_panel)
        
        dialog.exec()
        
    def _apply_settings_changes(self, settings_panel):
        """应用设置更改"""
        try:
            # 应用主题设置
            current_theme = settings_panel.theme_panel.theme_manager.get_current_theme()
            self.apply_theme(current_theme)
            
            # 获取主题类型
            theme_type = "light" if "light" in current_theme.lower() else "dark"
            
            # 更新导航按钮图标
            if hasattr(self, 'nav_buttons'):
                button_icons = {
                    "终端": f"terminal-{theme_type}.png",
                    "模版": f"model-{theme_type}.png",
                    "版本": f"version-{theme_type}.png",
                    "设置": f"setting-{theme_type}.png"
                }
                
                for btn in self.nav_buttons:
                    if btn.toolTip() in button_icons:
                        icon_path = os.path.join(os.path.dirname(__file__), 'static', 'icons', button_icons[btn.toolTip()])
                        btn.setIcon(QIcon(icon_path))
            
            # 更新会话树形列表图标
            if hasattr(self, 'session_list'):
                computer_icon = QIcon(os.path.join(os.path.dirname(__file__), 'static', 'icons', f'computer-{theme_type}.png'))
                folder_icon = QIcon(os.path.join(os.path.dirname(__file__), 'static', 'icons', f'folder-{theme_type}.png'))
                self.session_list.update_icons(computer_icon, folder_icon)
            
            # 应用终端设置
            settings_panel.terminal_panel.save_config()
            
            # 应用日志设置
            log_enabled = settings_panel.logger_panel.enable_logging.isChecked()
            log_dir = settings_panel.logger_panel.path_input.text()
            self.log_manager.set_logging_enabled(log_enabled)
            self.log_manager.set_log_dir(log_dir)
            
            # 显示保存成功提示
            from PySide6.QtWidgets import QMessageBox
            QMessageBox.information(self, "保存成功", "设置已成功保存！")
            
        except Exception as e:
            from PySide6.QtWidgets import QMessageBox
            QMessageBox.critical(self, "设置应用失败", f"应用设置时发生错误：{str(e)}")
    
    def show_about(self):
        """显示关于对话框"""
        from PySide6.QtWidgets import QMessageBox
        QMessageBox.about(self, '关于 ATerminal',
                         'ATerminal 是一个基于 PySide6 的终端模拟器，支持串口、SSH、Telnet等多种连接方式。')

def main():
    QCoreApplication.setAttribute(Qt.ApplicationAttribute.AA_ShareOpenGLContexts)
    QGuiApplication.setAttribute(Qt.ApplicationAttribute.AA_UseSoftwareOpenGL)
    QCoreApplication.setAttribute(Qt.ApplicationAttribute.AA_UseSoftwareOpenGL)
    QApplication.setAttribute(Qt.ApplicationAttribute.AA_UseSoftwareOpenGL)
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec())

if __name__ == "__main__":
    main()